(function() {

	var appModule = angular.module('tracecashModule');

	appModule.directive('searchPolicyList', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/search-policy/search-policy-list.html',
			controller : ['$scope', '$location', function($scope, $location) {
				$scope.goToPolicy = function(policy) {
					$location.path('newPolicyHost/' + policy.agreement.code + '/' + policy.filial + '/' + policy.number);
				};
			}],
			require : '^ngModel',
			scope : {
				searchResults : '=ngModel',
				title : '@'
			}
		};
	});

	appModule.controller('SearchPolicyCtrl', ['$scope', '$rootScope', '$http', 'MessageUtils', 'Utils', function($scope, $rootScope, $http, MessageUtils, Utils) {
		$scope.searchType = 'searchById';
		$scope.initial = angular.copy($scope.policySearchAction);
		$scope.clear = function() {
			angular.copy($scope.initial, $scope.policySearchAction);
			$scope.form.$setPristine();
		};
		$scope.search = function() {
			var action = $scope.policySearchAction;
			if ($scope.searchType == 'searchById' && Utils.isEmpty(action.idCard)) {
				$scope.message = MessageUtils.createError("validation.idCard.mandatory");
			} else if ($scope.searchType == 'searchByName' && Utils.isEmpty(action.surname)) {
				$scope.message = MessageUtils.createError("validation.surname.mandatory");
			} else if ($scope.searchType == 'searchByCertificate' && (Utils.isEmpty(action.agreement) && Utils.isEmpty(action.colectiva) && Utils.isEmpty(action.network) && Utils.isEmpty(action.number))) {
				$scope.message = MessageUtils.createError("validation.certificate.mandatory");
			} else {
				$scope.message = null;
			}
			if ($scope.message == null) {
				$scope.isLoading = true;
				$http.post($rootScope.REST_PATH + '/policy/searchHost', $scope.policySearchAction).success(function(searchResults) {
					$scope.hostSearchResults = searchResults;
					$scope.isLoading = false;
				});
//				$http.post($rootScope.REST_PATH + '/policy/searchPole', $scope.policySearchAction).success(function(searchResults) {
//					$scope.poleSearchResults = searchResults;
//					$scope.isLoading = false;
//				});
			}
		};
		$http.get($rootScope.REST_PATH + '/agreement/findAll').success(function(res) {
			$scope.agreements = res;
		});
	}]);

})();